<?php
/**
 * 合同仓库
 * @author wangwx 2015-5-12
 */
namespace common\repositories\common;

use Yii;
use yii\helpers\ArrayHelper;
use common\repositories\BaseRepository;
use common\entities\common\MyscrmOrganizationToPackageEntity;
use common\entities\common\MyscrmPackageEntity;
use common\entities\common\MyscrmPackagePriceEntity;
use common\entities\common\MyscrmPackageToApplicationEntity;
use common\support\StringHelper;

class MyscrmPackageRepository extends BaseRepository {

    /**
     * 添加应用套餐包
     * @param $pkgObj
     * @return bool|\Exception
     * @throws \Exception
     */
    public function addPackage($pkgObj){
        if(!array_key_exists('friendly_name', $pkgObj) || !array_key_exists('unique_name', $pkgObj)){
             throw $this->throwException("缺少参数");
        }
        $packageEntity = new MyscrmPackageEntity();
        $packageEntity['id'] = StringHelper::uuid();
        $packageEntity['friendly_name'] = ArrayHelper::getValue($pkgObj, 'friendly_name');
        $packageEntity['unique_name'] = ArrayHelper::getValue($pkgObj, 'unique_name');
        $t = date("Y-m-d H:i:s");
        $packageEntity['created_on'] = $t;
        $packageEntity['modified_on'] = $t;
        if(!Yii::$app->user->getIsGuest()){
            $packageEntity['created_by'] = Yii::$app->user->getIdentity()->getId();
            $packageEntity['modified_by'] = Yii::$app->user->getIdentity()->getId();
        }

        if($packageEntity->validate()){
            if($packageEntity->save()){
                return true;
            }
        }

        return $this->throwException($packageEntity->getFirstErrors());
    }


    /**
     * 返回所有package
     * @param string $sortField
     * @param int $order
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getPackages($sortField='', $order=SORT_ASC){
        if(empty($sortField)){
            $pkgs = MyscrmPackageEntity::find()
                ->all();
        }else{
            $pkgs = MyscrmPackageEntity::find()
                ->orderBy([$sortField => $order])
                ->all();
        }

        $newPkgs = [];
        if(!empty($pkgs)){
            foreach($pkgs as $pkg){
                $pkg = $pkg->toArray();
                $pkg['price'] = MyscrmPackagePriceEntity::getPackagePrice($pkg['id']);
                $newPkgs []= $pkg;
            }
        }

        return $newPkgs;
    }

    /**
     * 获取包的价格
     * @param $pkgId
     * @return array
     */
    public function getPackagePrice($pkgId){
        return ['price' => MyscrmPackagePriceEntity::getPackagePrice($pkgId)];
    }


    /**
     * 根据指定的package_id和application_id得到对应的一个application
     * @param $package_id
     * @param $application_id
     * @return null|static
     * @throws \Exception
     */
    private function getOneApplicationInPackage($package_id, $application_id){
        if(empty($package_id) || empty($application_id)){
            throw $this->throwException('缺少参数');
        }

        return MyscrmPackageToApplicationEntity::findOne([
            'package_id' => $package_id,
            'application_id' => $application_id
        ]);
    }

    /**
     * 添加app到package
     * @param $package_id
     * @param $application_id
     * @return bool
     * @throws \Exception
     */
    public function addApplicationToPackage($package_id, $application_id){
        if(empty($package_id) || empty($application_id)){
            throw $this->throwException('缺少参数');
        }

        if($this->getOneApplicationInPackage($package_id, $application_id)){
            throw $this->throwException("在package中已存在该产品");
        }

        $packageToApplication = new MyscrmPackageToApplicationEntity();
        $packageToApplication['id'] = StringHelper::uuid();
        $packageToApplication['package_id'] = $package_id;
        $packageToApplication['application_id'] = $application_id;
        $t = date("Y-m-d H:i:s");
        $packageToApplication['created_on'] = $t;
        $packageToApplication['modified_on'] = $t;
         if(!Yii::$app->user->getIsGuest()){
             $packageToApplication['created_by'] = Yii::$app->user->getIdentity()->getId();
             $packageToApplication['modified_by'] = Yii::$app->user->getIdentity()->getId();
        }

        if($packageToApplication->validate()){
            if($packageToApplication->save()){
                return true;
            }
        }

        throw $this->throwException($packageToApplication->getFirstErrors());

    }

    /**
     * 根据id得到包
     * @param $pkgId string 套餐包Id
     * @return null|static
     */
    public function getPackageById($pkgId){
        $pkg = MyscrmPackageEntity::findOne([
            "id" => $pkgId
        ]);
        if(!empty($pkg)){
            $pkg = $pkg->toArray();
            $pkg['price'] = MyscrmPackagePriceEntity::getPackagePrice($pkgId);
        }

        return $pkg;
    }

    /**
     * 返回指定包下面的所有application的id
     * @param $pkgId string 
     * @return static[]
     */
    public function getPackageApplicationIds($pkgId){
        return MyscrmPackageToApplicationEntity::find()->select(["application_id"])->where(['package_id' => $pkgId])->all();
    }

    /**
     * 在指定的package中删除application
     * @param $package_id
     * @param $application_id
     * @return int
     */
    public function delApplicationInPackage($package_id, $application_id){
        return MyscrmPackageToApplicationEntity::deleteAll('package_id=:pkg_id AND application_id=:app_id', ['pkg_id' => $package_id, 'app_id' => $application_id]);
    }

    /**
     * 更新package的price，如果不存在就插入
     * @param $package_id
     * @param $price
     * @param $unit
     * @return bool
     * @throws \Exception
     */
    public function upsertPackagePrice($package_id, $price, $unit){

        $pkgPrice = MyscrmPackagePriceEntity::findOne([
            'package_id' => $package_id
        ]);
        if(empty($pkgPrice)){
            $pkgPrice = new MyscrmPackagePriceEntity();
            $pkgPrice['package_id'] = $package_id;
        }
        $pkgPrice['price'] = $price;
        $pkgPrice['unit'] = $unit;
        $pkgPrice['id'] = StringHelper::uuid();
        $t = date("Y-m-d H:i:s");
        $pkgPrice['created_on'] = $t;
        $pkgPrice['modified_on'] = $t;
        if(!Yii::$app->user->getIsGuest()){
            $pkgPrice['created_by'] = Yii::$app->user->getIdentity()->getId();
            $pkgPrice['modified_by'] = Yii::$app->user->getIdentity()->getId();
        }
        if($pkgPrice->save()){
            return true;
        }else{
            throw $this->throwException($pkgPrice->getFirstErrors());
        }

    }

    /**
     * 根据客户ID得到他购买的package
     * @param $orgId
     * @return static[]
     */
    public function getPackageByOrgId($orgId){
        return MyscrmOrganizationToPackageEntity::findAll([
            'organization_id' => $orgId,
        ]);
    }

    /**
     * 根据商户ID和package_id得到他购买的package
     * @param $orgId
     * @param $packageId$packageId
     * @return static[]
     */
    public function getPackageByOrgIdAndPkgId($orgId, $packageId){
        return MyscrmOrganizationToPackageEntity::findAll([
            'organization_id' => $orgId,
            'package_id' => $packageId
        ]);
    }

    /**
     * 根据UniqueName得到包
     * @param $uniqueName
     * @return null|static
     */
    public function getPackageByUniqueName($uniqueName){
        return MyscrmPackageEntity::findOne([
            "unique_name" => $uniqueName
        ]);
    }

}

